<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/pace-js@1/themes/blue/pace-theme-minimal.css">
  <script src="//cdn.jsdelivr.net/npm/pace-js@1/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yimig.github.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="瞎写一时爽，维护火葬场  天天写尸堆，自己都看不下去了！什么时候开始自己的代码变得那么丑陋了呢？经过一番回想，我发现凡是没有约束的代码，变得丑陋只是时间问题。 综上所述，我拜读了Joost Visser的Building Maintainable Software这本书（中文译名为“代码不朽”），受益匪浅，在此做一下笔记以防遗忘。">
<meta property="og:type" content="article">
<meta property="og:title" content="【读书笔记】代码不朽——编写可维护软件的十大要则">
<meta property="og:url" content="http://yimig.github.io/2019/03/09/note_long_live_coding/index.html">
<meta property="og:site_name" content="Tim&#39;s Blog">
<meta property="og:description" content="瞎写一时爽，维护火葬场  天天写尸堆，自己都看不下去了！什么时候开始自己的代码变得那么丑陋了呢？经过一番回想，我发现凡是没有约束的代码，变得丑陋只是时间问题。 综上所述，我拜读了Joost Visser的Building Maintainable Software这本书（中文译名为“代码不朽”），受益匪浅，在此做一下笔记以防遗忘。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-03-09T13:26:44.000Z">
<meta property="article:modified_time" content="2020-10-28T14:50:57.472Z">
<meta property="article:author" content="Tim">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yimig.github.io/2019/03/09/note_long_live_coding/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【读书笔记】代码不朽——编写可维护软件的十大要则 | Tim's Blog</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64126ab668fa908027cba9464a0afec7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Tim's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Learn Everything!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-schedule">

    <a href="/schedule/" rel="section"><i class="fa fa-fw fa-calendar"></i>日程表</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/yimig" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yimig.github.io/2019/03/09/note_long_live_coding/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/avatar.png">
      <meta itemprop="name" content="Tim">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tim's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【读书笔记】代码不朽——编写可维护软件的十大要则
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-03-09 21:26:44" itemprop="dateCreated datePublished" datetime="2019-03-09T21:26:44+08:00">2019-03-09</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-10-28 22:50:57" itemprop="dateModified" datetime="2020-10-28T22:50:57+08:00">2020-10-28</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Life/" itemprop="url" rel="index"><span itemprop="name">Life</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Life/Note/" itemprop="url" rel="index"><span itemprop="name">Note</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              <span>7.5k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              <span>7 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<p>瞎写一时爽，维护火葬场</p>
</blockquote>
<p>天天写尸堆，自己都看不下去了！什么时候开始自己的代码变得那么丑陋了呢？经过一番回想，我发现凡是没有约束的代码，变得丑陋只是时间问题。 综上所述，我拜读了Joost Visser的Building Maintainable Software这本书（中文译名为“代码不朽”），受益匪浅，在此做一下笔记以防遗忘。<br><a id="more"></a></p>
<h1 id="代码不朽"><a href="#代码不朽" class="headerlink" title="代码不朽"></a>代码不朽</h1><h2 id="——编写可维护软件的十大要则"><a href="#——编写可维护软件的十大要则" class="headerlink" title="——编写可维护软件的十大要则"></a>——编写可维护软件的十大要则</h2><hr>
<h3 id="①编写较小的代码单元"><a href="#①编写较小的代码单元" class="headerlink" title="①编写较小的代码单元"></a>①编写较小的代码单元</h3><h4 id="原则："><a href="#原则：" class="headerlink" title="原则："></a>原则：</h4><ul>
<li><strong>代码单元的长度应该限制在15行代码以内。</strong></li>
<li>为此首先<strong>不要编写超过15行代码的单元，或者将长的单元分解成多个更短的单元</strong>，直到每个单元都不超过15行代码。</li>
<li>该原则能提高可维护性的原因在于，<strong>短小的代码但愿易于理解，测试及重用。</strong></li>
</ul>
<h4 id="如何应用本原则？"><a href="#如何应用本原则？" class="headerlink" title="如何应用本原则？"></a>如何应用本原则？</h4><p><strong>——使用重构技巧来应用原则</strong></p>
<h5 id="㈠重构技巧：提取方法"><a href="#㈠重构技巧：提取方法" class="headerlink" title="㈠重构技巧：提取方法"></a>㈠重构技巧：提取方法</h5><p>将内容代码较多的单元提取为几个代码较少的单元，此时代码总量将增加，但是我们总要在代码总量与后期可维护性之间做出权衡，不止这里，后面讲的方法也或多或少地增加了代码总量，但却能大大提高后期可维护性。 <strong>Example——吃豆人游戏中的一段代码：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(inProgress)&#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    inProgress=<span class="keyword">true</span>;</span><br><span class="line">    <span class="comment">//如果玩家死亡则更新观察者</span></span><br><span class="line">    <span class="keyword">if</span>(!isAnyPlayerAlive())&#123;</span><br><span class="line">        <span class="keyword">for</span>(LevelOvserver o:observers)&#123;</span><br><span class="line">            o.levelLost();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//如果所有的豆都被吃光则更新观察者</span></span><br><span class="line">    <span class="keyword">if</span>(remainingPellets()==<span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">for</span>(LevelObserver o:observers)&#123;</span><br><span class="line">            o.levelWon();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>原来有1行代码，现在我们提取方法，可将其分解成三个小方法：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(inProgress)&#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    inProgress=<span class="keyword">true</span>;</span><br><span class="line">    updateObservers();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">updateObservers</span><span class="params">()</span></span>&#123;</span><br><span class="line">    updateObserversPlayerDied();</span><br><span class="line">    updateObserversPelletsEaten();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">updateOberversPlayerDied</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(!isAnyPlayerAlive())&#123;</span><br><span class="line">        <span class="keyword">for</span>(LevelObserver o:observers)&#123;</span><br><span class="line">            o.levelLost();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">updateObserversPelletsEaten</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(remainingPellets()==<span class="number">0</span>)&#123;</span><br><span class="line">        <span class="keyword">for</span>(LevelObserver o:observers)&#123;</span><br><span class="line">            o.levelWon();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="㈡重构技巧：将方法替换为方法对象"><a href="#㈡重构技巧：将方法替换为方法对象" class="headerlink" title="㈡重构技巧：将方法替换为方法对象"></a>㈡重构技巧：将方法替换为方法对象</h5><p>在传入参数较少时使用提取方法较为方便，上面的例子就提取出了三个无参数的函数。但是若是要提取的方法调用了较多临时变量，提取方法时就要传入大量参数，造成代码冗余，对于这种情况可以尝试<strong>将方法替换为方法对象</strong> <strong>Example：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Board <span class="title">CreatBoard</span><span class="params">(Square[][] grid)</span></span>&#123;</span><br><span class="line">    <span class="keyword">assert</span> grid!=<span class="keyword">null</span>;</span><br><span class="line">    Board board=<span class="keyword">new</span> Board(grid);</span><br><span class="line">    <span class="keyword">int</span> width=board.getWidth();</span><br><span class="line">    <span class="keyword">int</span> height=board.getHeight();</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> x=<span class="number">0</span>;x&lt;width;x++)&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> y=<span class="number">0</span>;y&lt;height;y++)&#123;</span><br><span class="line">            Square square=grid[x][y];</span><br><span class="line">            <span class="keyword">for</span>(Direction dir:Direction.velues())&#123;</span><br><span class="line">                <span class="keyword">int</span> dirX=(width+x+dir.getDeltaX())%width;</span><br><span class="line">                <span class="keyword">int</span> dirY=(height+y+dir.getDeltaY())%height;</span><br><span class="line">                Square neighbour=grid[dirX][dirY];</span><br><span class="line">                square.link(neighbour,dir);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>若要提取上面循环中的方法，则需要传递七个参数，分别是<code>width</code>,<code>height</code>,<code>x</code>,<code>y</code>,<code>dir</code>,<code>square</code>,<code>grid</code>。拥有很长参数的方法显得丑陋无比，下面使用方法对象来将其替换之：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BoardCreator</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Square[][] grid;</span><br><span class="line">    <span class="keyword">private</span> Board borad;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> width;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> height;</span><br><span class="line">    BoardCreator(Square[][] grid)&#123;</span><br><span class="line">        <span class="keyword">assert</span> grid!=<span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">this</span>.grid=grid;</span><br><span class="line">        <span class="keyword">this</span>.board=<span class="keyword">new</span> Board(grid);</span><br><span class="line">        <span class="keyword">this</span>.width=board.getWidth();</span><br><span class="line">        <span class="keyword">this</span>.height=board.getHeight();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function">Board <span class="title">create</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> x=<span class="number">0</span>;x&lt;width;x++)&#123;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> y=<span class="number">0</span>;y&lt;height;y++)&#123;</span><br><span class="line">                Square square =grid[x][y];</span><br><span class="line">                <span class="keyword">for</span>(Direction dir:Direction.values())&#123;</span><br><span class="line">                    setLink(Square,dir,x,y);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.board;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">setLink</span><span class="params">(Square square,Direction dir,<span class="keyword">int</span> x,<span class="keyword">int</span> y)</span></span>&#123;</span><br><span class="line">        <span class="keyword">int</span> dirX=(width+x+dir.getDeltaX())%width;</span><br><span class="line">        <span class="keyword">int</span> dirY=(height+y+dir.getDeltaY())%height;</span><br><span class="line">        Square neighbour=grid[dirX][dirY];</span><br><span class="line">        square.link(neighbour,dir);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如此，有了以上方法类，<code>createBoard</code>方法即可重构为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Board <span class="title">createBoard</span><span class="params">(Square[][] grid)</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> BoardCreator(grid).create();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="本章警告："><a href="#本章警告：" class="headerlink" title="本章警告："></a>本章警告：</h4><blockquote>
<p>⑴不要牺牲可维护性来优化性能，除非有可靠的性能测试能够证明确实存在性能问题，并且你的性能优化措施也真的有效果。 ⑵为你的继任者（也为将来的自己）编写易于阅读和理解的代码。 ⑶当似乎可以重构但是并没有什么意义时，请重新思考系统的架构。 ⑷精挑细选可以描述功能的方法名，并将代码放在短小的代码单元中（最多15行代码）。</p>
</blockquote>
<h3 id="②编写简单的代码单元"><a href="#②编写简单的代码单元" class="headerlink" title="②编写简单的代码单元"></a>②编写简单的代码单元</h3><h4 id="原则：-1"><a href="#原则：-1" class="headerlink" title="原则："></a>原则：</h4><ul>
<li><strong>限制每个代码单元分支点的数量不超过4个。</strong></li>
<li>你应该<strong>将复杂的代码单元拆分成多个简单的单元</strong>，避免多个复杂的单元在一起。</li>
<li>该原则能提高可维护性的原因在于，分支点越少，<strong>代码单元越容易被修改和测试。</strong></li>
</ul>
<h4 id="概念："><a href="#概念：" class="headerlink" title="概念："></a>概念：</h4><ul>
<li><strong>代码单元分支点： 能够覆盖分支点所有分支的路径数量。</strong> 在Java中，这些语句均被认为是分支点：<ol>
<li>if</li>
<li>case</li>
<li>?</li>
<li>&amp;&amp;,</li>
<li>while</li>
<li>for</li>
<li>catch</li>
</ol>
</li>
<li><strong>McCabe复杂度：分支点数量加一</strong> ，又称圈复杂度或循环复杂度。因此这个原则相当于“限制McCabe复杂度不超过5”。</li>
</ul>
<h4 id="如何使用本原则？"><a href="#如何使用本原则？" class="headerlink" title="如何使用本原则？"></a>如何使用本原则？</h4><h5 id="Ⅰ-处理链式条件语句"><a href="#Ⅰ-处理链式条件语句" class="headerlink" title="Ⅰ.处理链式条件语句"></a>Ⅰ.处理链式条件语句</h5><p>以以下代码为例。对于一个国家来说，<code>getFlagColors</code>方法会返回正确的国旗颜色：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Color&gt; <span class="title">getFlagColors</span><span class="params">(Nationality notionality)</span></span>&#123;</span><br><span class="line">    List&lt;Color&gt; result;</span><br><span class="line">    <span class="keyword">switch</span>(nationality)&#123;</span><br><span class="line">        <span class="keyword">case</span> DUTCH:</span><br><span class="line">            result=Arrays.asList(Color.RED,Color.WHITE,Color.BLUE);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> GERMAN:</span><br><span class="line">            result=Arrays.asList(Color.BLACK,Color.RED,Color.YELLOW);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> BELGIAN:</span><br><span class="line">            result=Arrays.asList(Color.BLACK,Color.YELLOW,Color.RED);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> FRENCH:</span><br><span class="line">            result=Arrays.asList(Color.BLUE,Color.WHITE,Color.RED);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> ITALIAN:</span><br><span class="line">            result=Arrays.asList(Color.GREEN,Color.WHITE,Color.RED);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> UNCLASSIFIED;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            result=Arrays.asList(Color.GRAY);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>显然，该方法的复杂度达到了6+1=7，我们需要对其进行优化。 <strong>方法一：引入一个Map数据结构：</strong> 这种方法的核心观念是：<strong>创建一个字典，以便使用一值直接映射到另一个值，从而将判断语句省略。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Map&lt;Nationality,List&lt;Color&gt;&gt; FLAGS=<span class="keyword">new</span> HashMap&lt;Nationality,List&lt;Color&gt;&gt;();</span><br><span class="line"><span class="keyword">static</span>&#123;</span><br><span class="line">    Flags.put(DUTCH,Arrays.asList(Color.RED,Color.WHITE,Color.BLUE));</span><br><span class="line">    Flags.put(GERMAN,Arrays.asList(Color.BLACK,Color.RED,Color.YELLOW));</span><br><span class="line">    Flags.put(BELGIAN,Arrays.asList(Color.BLACK,Color.YELLOW,Color.RED));</span><br><span class="line">    Flags.put(FRENCH,Arrays.asList(Color.BLUE,Color.WHITE,Color.RED));</span><br><span class="line">    Flags.put(ITALIAN,Arrays.asList(Color.GREEN,Color.WHITE,Color.RED));</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Color&gt; <span class="title">getFlagColors</span><span class="params">(Nationality nationality)</span></span>&#123;</span><br><span class="line">    List&lt;Color&gt; color=FLAGS.get(nationality);</span><br><span class="line">    <span class="keyword">return</span> colors!=<span class="keyword">null</span>?colors:Arrays.asList(Color.GRAY);<span class="number">8</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>方法二：使用多态来代替条件判断</strong> 这种方法的核心观念是：<strong>让每个国旗都拥有一个自己的类型，并实现同一个接口。Java语言的多态性会保证在运行时调用到正确的类型。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//为了进行这次重构，我们首先定义一个共用的Flag接口</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Flag</span></span>&#123;</span><br><span class="line">    <span class="function">List&lt;Color&gt; <span class="title">getColors</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//为不同的国家定义不同的国旗类型，例如荷兰国旗：</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DutchFlag</span> <span class="keyword">implements</span> <span class="title">Flag</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Color&gt; <span class="title">getColors</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Arrays.asList(Color.RED,Color.WHITE,Color.BLUE);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//以及意大利国旗：</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ItalianFlag</span> <span class="keyword">implements</span> <span class="title">Flag</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;color&gt; <span class="title">getColors</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Arrays.asList(Color.GREEN,Color.WHITE,Color.RED);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//中间的国旗类定义不予赘述</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="title">Map</span><span class="params">(Nationality nationality)</span></span>&#123;&#125;</span><br><span class="line"><span class="keyword">static</span>&#123;</span><br><span class="line">    Flags.put(DUTCH,<span class="keyword">new</span> DutchFlag());</span><br><span class="line">    Flags.put(GERMAN,<span class="keyword">new</span> GermanFlag());</span><br><span class="line">    Flags.put(BELGIAN,<span class="keyword">new</span> BelgianFlag());</span><br><span class="line">    Flags.put(FRENCH,<span class="keyword">new</span> FrenchFlag());</span><br><span class="line">    Flags.put(ITALIAN,<span class="keyword">new</span> ItalianFlag());</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Color&gt; <span class="title">getFlagColors</span><span class="params">(Nationality nationality)</span></span>&#123;</span><br><span class="line">    Flag flag=FLAGS.get(nationality);</span><br><span class="line">    flag=flag!=<span class="keyword">null</span>?flag:<span class="keyword">new</span> DefaultFlag();</span><br><span class="line">    <span class="keyword">return</span> flag.getColors();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这种重构技巧提供了最灵活的实现方式，例如，你只需要实现新的国旗类型，就可以不断增加所支持的国旗种类，并且可以对它进行独立测试。不过这种方式的不好之处是引入了更多的类和代码。开发人员必须在可扩展性和简洁性之间做出选择。</p>
<h5 id="Ⅱ-嵌套条件语句"><a href="#Ⅱ-嵌套条件语句" class="headerlink" title="Ⅱ.嵌套条件语句"></a>Ⅱ.嵌套条件语句</h5><p>如下例所示，我们给定一个二分查找树的根节点和一个整数，<code>calculateDepth</code>方法会找出整数在树中的位置。如果找到，该方法会返回整数在树中的深度，否则抛出一个TreeException异常：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">calculateDepth</span><span class="params">(BinaryTreeNode&lt;Integer&gt;t,<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> depth=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span>(t.getValue()==n)&#123;</span><br><span class="line">        retrun depth;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(n&lt;t.getValue())&#123;</span><br><span class="line">            BinaryTreeNode&lt;Inter&gt; left=t.getLeft();</span><br><span class="line">            <span class="keyword">if</span>(left=<span class="keyword">null</span>)&#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> TreeException(<span class="string">&quot;Value not found in tree!&quot;</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="number">1</span>+calculateDepth(Left,n);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            BinaryTreeNode&lt;Inter&gt; right=t.getRight();</span><br><span class="line">            <span class="keyword">if</span>(right==<span class="keyword">null</span>)&#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> TreeException(<span class="string">&quot;Value not found in tree!&quot;</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="number">1</span>+calculateDepth(right,n);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>为了<strong>提高可读性</strong>，我们可以标识出各种独立的情况，并插入<code>return</code>语句来代替嵌套式的条件语句，这种做法在重构中被称为<strong>使用卫语句来代替嵌套的条件语句</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">calculateDepth</span><span class="params">(BinaryTreeNode&lt;Integer&gt; t,<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> depth=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span>(t.getValue()==n)<span class="keyword">return</span> depth;</span><br><span class="line">    <span class="keyword">if</span>(n&lt;getValue()&amp;&amp;t.getLeft()!=<span class="keyword">null</span>)<span class="keyword">return</span> <span class="number">1</span>+calculateDepth(t.getLeft(),n);</span><br><span class="line">    <span class="keyword">if</span>(n&lt;getValue()&amp;&amp;t.getRight()!=<span class="keyword">null</span>)<span class="keyword">return</span> <span class="number">1</span>+calculateDepth(t.getRight(),n);</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> TreeException(<span class="string">&quot;Value not found in tree!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样一来，代码就变得更容易理解了，<strong>但是其复杂度并没有降低</strong>，为了降低复杂度，应该<strong>将嵌套的条件语句提取到其他方法中</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">calculateDepth</span><span class="params">(BinaryTreeNode&lt;Integer&gt; t <span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> depth=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span>(t.getValue()==n)<span class="keyword">return</span> depth;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">return</span> traverseByValue(t,n);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">traverseByValue</span><span class="params">(BinaryTreeNode&lt;Integer&gt; t,<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    BinaryTreeNode&lt;Integer&gt; childNode=getChildNode(t,n);</span><br><span class="line">    <span class="keyword">if</span>(childNode==Null)&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> TreeException(<span class="string">&quot;Value not found in tree!&quot;</span>);</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>+calculateDepth(childNode,n);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> BinaryTreeNode&lt;Integer&gt; <span class="title">getChildNode</span><span class="params">(BinaryTreeNode&lt;Integer&gt; t,<span class="keyword">int</span> n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(n&lt;t.getValue())<span class="keyword">return</span> t.getLeft();</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">return</span> t.getRight();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>&lt;====To be continue====&gt;</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java/" rel="tag"># Java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/02/10/tutorial_wpt2/" rel="prev" title="【教程】Walkman Playlist Tools使用教程（第二版）">
      <i class="fa fa-chevron-left"></i> 【教程】Walkman Playlist Tools使用教程（第二版）
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/04/21/js_note1/" rel="next" title="【JS】js学习小笔记 1#">
      【JS】js学习小笔记 1# <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E4%B8%8D%E6%9C%BD"><span class="nav-number">1.</span> <span class="nav-text">代码不朽</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E2%80%94%E2%80%94%E7%BC%96%E5%86%99%E5%8F%AF%E7%BB%B4%E6%8A%A4%E8%BD%AF%E4%BB%B6%E7%9A%84%E5%8D%81%E5%A4%A7%E8%A6%81%E5%88%99"><span class="nav-number">1.1.</span> <span class="nav-text">——编写可维护软件的十大要则</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E2%91%A0%E7%BC%96%E5%86%99%E8%BE%83%E5%B0%8F%E7%9A%84%E4%BB%A3%E7%A0%81%E5%8D%95%E5%85%83"><span class="nav-number">1.1.1.</span> <span class="nav-text">①编写较小的代码单元</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E5%88%99%EF%BC%9A"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">原则：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E5%BA%94%E7%94%A8%E6%9C%AC%E5%8E%9F%E5%88%99%EF%BC%9F"><span class="nav-number">1.1.1.2.</span> <span class="nav-text">如何应用本原则？</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E3%88%A0%E9%87%8D%E6%9E%84%E6%8A%80%E5%B7%A7%EF%BC%9A%E6%8F%90%E5%8F%96%E6%96%B9%E6%B3%95"><span class="nav-number">1.1.1.2.1.</span> <span class="nav-text">㈠重构技巧：提取方法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E3%88%A1%E9%87%8D%E6%9E%84%E6%8A%80%E5%B7%A7%EF%BC%9A%E5%B0%86%E6%96%B9%E6%B3%95%E6%9B%BF%E6%8D%A2%E4%B8%BA%E6%96%B9%E6%B3%95%E5%AF%B9%E8%B1%A1"><span class="nav-number">1.1.1.2.2.</span> <span class="nav-text">㈡重构技巧：将方法替换为方法对象</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%9C%AC%E7%AB%A0%E8%AD%A6%E5%91%8A%EF%BC%9A"><span class="nav-number">1.1.1.3.</span> <span class="nav-text">本章警告：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E2%91%A1%E7%BC%96%E5%86%99%E7%AE%80%E5%8D%95%E7%9A%84%E4%BB%A3%E7%A0%81%E5%8D%95%E5%85%83"><span class="nav-number">1.1.2.</span> <span class="nav-text">②编写简单的代码单元</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E5%88%99%EF%BC%9A-1"><span class="nav-number">1.1.2.1.</span> <span class="nav-text">原则：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A6%82%E5%BF%B5%EF%BC%9A"><span class="nav-number">1.1.2.2.</span> <span class="nav-text">概念：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E6%9C%AC%E5%8E%9F%E5%88%99%EF%BC%9F"><span class="nav-number">1.1.2.3.</span> <span class="nav-text">如何使用本原则？</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E2%85%A0-%E5%A4%84%E7%90%86%E9%93%BE%E5%BC%8F%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5"><span class="nav-number">1.1.2.3.1.</span> <span class="nav-text">Ⅰ.处理链式条件语句</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E2%85%A1-%E5%B5%8C%E5%A5%97%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5"><span class="nav-number">1.1.2.3.2.</span> <span class="nav-text">Ⅱ.嵌套条件语句</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Tim"
      src="/uploads/avatar.png">
  <p class="site-author-name" itemprop="name">Tim</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">90</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">40</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yimig" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yimig" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:zhangyiming@programmer.net" title="E-Mail → mailto:zhangyiming@programmer.net" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://leetcode.com/yimig/" title="LeeCode → https:&#x2F;&#x2F;leetcode.com&#x2F;yimig&#x2F;" rel="noopener" target="_blank"><i class="fa fa-fw fa-code"></i>LeeCode</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/tim-2-96" title="zhihu → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;tim-2-96" rel="noopener" target="_blank"><i class="fa fa-fw fa-question-circle"></i>zhihu</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://upane.cn/" title="https:&#x2F;&#x2F;upane.cn" rel="noopener" target="_blank">博客旧址</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tim</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">183k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:46</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_sphere.min.js"></script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : 'a876807f33858291f9d9',
      clientSecret: '7a5c6a83611c309965d7339d7ca5f16e34a21e9f',
      repo        : 'yimig.github.io',
      owner       : 'yimig',
      admin       : ['yimig'],
      id          : '2dd548263eb1a7f190327cb959266ffc',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

</body>
</html>
